$(function () {
    /*项目路径*/
    var baseURL = /knowledge/
    totalSize = 0;
    var currentSize = 0
    /*日期*/
/*    jeDate("#documentUploadDate", {
        format: "YYYY-MM-DD hh:mm:ss",
        isTime: false,
        minDate: "2014-09-19 00:00:00"
    });*/
    $('.js-example-basic-multiple').select2();
    /*上传插件*/

    /*构建列表*/
    $("#jqGrid").jqGrid({
        url: baseURL + '/document/getDocumentList',
        datatype: "json",
        colModel: [
			{label: '编号',name : 'documentId',index : "documentId",width : 20,key : true},
			{label: '标题', name: 'documentTitle', index: "documentTitle", width: 45},
            {label: '来源', name: 'documentOrigin', index: "documentOrigin", width: 45},
            {label: '作者', name: 'documentAuthor', width: 75},
            {label: '摘要', name: 'documentAbstract', width: 100},
            {
                label: '审批状态', name: 'documentState', width: 80, formatter: function (value, options, row) {
                    if (value == 0) {
                        return '<span class="label label-info">等待审核</span>';
                    }
                    if (value == 1) {
                        return '<span class="label label-success">审核通过</span>';
                    }
                    if (value == 2) {
                        return '<span class="label label-danger">审核不过</span>';
                    }
                }
            },
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: false,
        /*rownumWidth: 25,*/
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.pageNum",
            total: "page.pages",
            records: "page.total"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });

	$('#easyContainer').easyUpload({
		//allowFileTypes: '*.pdf;*.doc;*.docx;*.ppt;*.pptx;xlsx;xls',//允许上传文件类型，格式';*.pdf;*.doc;*.docx;*.jpg;*.png'
		allowFileTypes: '*.*',//允许上传文件类型，格式';*.pdf;*.doc;*.docx;*.jpg;*.png'
		allowFileSize: 100000,//允许上传文件大小(KB)
		selectText: '选择文件',//选择文件按钮文案
		multi: true,//是否允许多文件上传
		multiNum: 5,//多文件上传时允许的文件数
		showNote: true,//是否展示文件上传说明
		note: '提示：最多上传5个文件，支持格式为doc、pdf',//文件上传说明
		showPreview: true,//是否显示文件预览
		url: baseURL + 'uploadFile',//上传文件地址
		fileName: 'file',//文件filename配置参数
		formParam: {
			//token: $.cookie('token_cookie')//不需要验证token时可以去掉
		},//文件filename以外的配置参数，格式：{key1:value1,key2:value2}
		timeout: 30000,//请求超时时间
		successFunc: function (res) {
			console.log('成功回调', res);
			if (res.success.length > 0 && res.success[0].code) {
				/*计数*/
				//alert("totalSize"+totalSize)
				// alert("currentSize"+currentSize)
				debugger
				if (currentSize == totalSize) {
					/*重置计数值*/
					currentSize = 0
					totalSize = 0
					/*调用刷新*/
					alert('新增成功！', function(){
						//vm.reload();
						/*解决表单数据没有清空*/
						location.reload()
					});
				}
				currentSize += 1
			}
		},//上传成功回调函数
		errorFunc: function (res) {
			console.log('失败回调', res);
		},//上传失败回调函数
		deleteFunc: function (res) {
			console.log('删除回调', res);
		}//删除文件回调函数
	});
})
/**************ztree  start*****************************/
var deptZtree;
var deptSetting = {
	data: {
		simpleData: {
			enable: true,
			idKey: "deptid",
			pIdKey: "preid",
			rootPId: "-1"
		}
	},
	callback: {
		beforeClick: function(treeId, treeNode) {
			deptZtree = $.fn.zTree.init($("#deptTree"),deptSetting, zNodes);
			//展开所有节点
			deptZtree.expandAll(true);
		}
	},
	check: {
        enable: true,
        //chkStyle: "radio",  //单选框
        chkStyle: "checkbox",  //单选框
        radioType: "all"   //对所有节点设置单选
    }
};

var userZtree;
var userSetting = {
		data: {
			simpleData: {
				enable: true,
				idKey: "userid",
				pIdKey: "preid",
				rootPId: "-1"
			}
		},
		callback: {
			beforeClick: function(treeId, treeNode) {
			    userZtree = $.fn.zTree.init($("#userTree"),userSetting, zNodes);
				//展开所有节点
				userZtree.expandAll(true);
			}
		},
		check: {
			enable: true,
			//chkStyle: "radio",  //单选框
			chkStyle: "checkbox",  //单选框
			radioType: "all"   //对所有节点设置单选
		}
};

var userSelect = new Array()
var deptSelect = new Array()
var up = 0;
var bt = 0;
/**************ztree  end*****************************/



var vm = new Vue({
    el: '#rrapp',
    data: {
        q: {
            key: null
        },
        showList: true,
		showUserList:true,
		showDeptList:true,
		showFormList:true,
        title: null,
        types:[],
        selected:null,
        lableList:[],
        document: {
            //documentUploadDate: null,
            documentAbstract: null,
            documentId : null,
        },
		userList : [],
		deptList : [],
		user:{},
		dept:{},
		userSelected : null,
		deptSelected : null
    },
    methods: {
        query: function () {
            vm.reload();
        },
        reload: function () {
            vm.showList = true;
			vm.showUserList=true;
			vm.showDeptList=true;
			vm.showFormList=true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData:{'key': vm.q.key},
                page: page
            }).trigger("reloadGrid");
        },
        add: function () {
            vm.showList = false;
			vm.showUserList=true;
			vm.showDeptList=true;
			vm.showFormList=false;
            
            vm.title = "新增";
            //vm.documentTypes(); 20180929移除文档类型
            vm.getAllLable();
            vm.getLoginUserInfo();
        },
        getLoginUserInfo:function(){
			$.get(baseURL + "document/getLoginUserInfo", function(r) {
				debugger
				if(r.user!=null){
					console.log(r.user.userName)
					console.log(r)
					vm.document.documentAuthor=r.user.userName
				}
			});
        },
        validator: function () {
        	if (isBlank(vm.document.documentTitle)) {
        		alert("标题不能为空");
        		return true;
        	}
            if (isBlank(vm.document.documentOrigin)) {
                alert("来源不能为空");
                return true;
            }
            if (isBlank(vm.document.documentAuthor)) {
                alert("作者不能为空");
                return true;
            }
//            if ($("#documentUploadDate").val().trim() == "") {
//                alert("时间不能为空");
//                return true;
//            }
//            if (isBlank(vm.selected)) {
//            	alert("类型不能为空");
//            	return true;
//            }
            if (isBlank(vm.document.documentKeyword)) {
                alert("关键词不能为空");
                return true;
            }
            if (isBlank(vm.document.documentAbstract)) {
                alert("摘要不能为空");
                return true;
            }

            if (isBlank(vm.document.documentMarks)) {
                alert("备注不能为空");
                return true;
            }

        },
        documentTypes:function(){
        	$.get(baseURL+"/documentType/getDocumnetTypes",function(r){
        		console.log(r)
        		vm.types=r.types;
        	})
        },
        getAllLable:function(){
        	$.get(baseURL+"/label/getAllLable",function(r){
        		vm.lableList=r.lableList;
        		console.log(r.lableList)
        	})
        }
        /*********** 发布  start*************/
        ,
		preReleaseToDept : function() {
			var documentId = getSelectedRow();
			if (documentId == null) {
				return;
			}
			vm.showList = false;
			vm.showDeptList = false;
			vm.showUserList = true;
			vm.showFormList=true;
			vm.title = "文档发布";
			// 获取角色信息
			//this.getUserAndDept();
			vm.document.documentId=documentId
			//vm.hello()
			vm.getDetpMap()
		},
		preReleaseToUser : function() {
			var documentId = getSelectedRow();
			if (documentId == null) {
				return;
			}
			vm.showList = false;
			vm.showDeptList = true;
			vm.showUserList = false;
			vm.showFormList=true;
			vm.title = "文档发布";
			// 获取角色信息
			vm.document.documentId=documentId
			vm.getUserMap()
		},
		userAll:function(){/*用户全选*/
			if(up==0){
				for(var i=0; i<userSelect.length; i++) {
					var node = ztree.getNodeByParam("userid", userSelect[i]);
					ztree.checkNode(node, true, false);
				}
				up = 1;
			}else{
				for(var i=0; i<userSelect.length; i++) {
					var node = ztree.getNodeByParam("userid", userSelect[i]);
					ztree.checkNode(node, false, false);
				}
				up = 0;
			}
		},
		userRelease:function(){/*用户发布*/
			var userTreeObj = $.fn.zTree.getZTreeObj("userTree");
            var userNodes = userTreeObj.getCheckedNodes(true);

            debugger
			console.log("vm.document.documentId   :"+vm.document.documentId)
			if (userNodes.length==0) {
				alert("发布人不能为空");
				return true;
			}
			var msg = null;
			
			var userArray=[]
			if (userNodes.length>0) {
				for(var j=0;j<userNodes.length;j++){
					var user={}
	                 if(!userNodes[j].isParent){//父节点不保存
	                    user.userid=userNodes[j].userid
	                    user.username=userNodes[j].name
	                    userArray.push(user)
	                 }
				}
				msg = "确定发布么？";
				var userdept={}
				userdept.userArray=userArray;
				userdept.documentId=vm.document.documentId
				//
				vm.commonRelease(msg,userdept);
			}
		},
		userTakeBack:function(){/*用户收回*/
            var userTreeObj = $.fn.zTree.getZTreeObj("userTree");
            var userNodes = userTreeObj.getCheckedNodes(true);

            debugger
            console.log("vm.document.documentId   :"+vm.document.documentId)
            if (userNodes.length==0) {
                alert("收回对象不能为空");
                return false;
            }
            var msg = null;

            var userArray=[]
            if (userNodes.length>0) {
                for(var j=0;j<userNodes.length;j++){
                    var user={}
                    user.userid=userNodes[j].userid
                    user.username=userNodes[j].name
                    userArray.push(user)
                }
                msg = "确定要回收么？";
                var userInfo={}
                userInfo.userArray=userArray;
                userInfo.documentId=vm.document.documentId
                vm.commonTakeBack(msg,userInfo);
            }
		},
		deptAll : function() {/*部门全选*/
			if(bt==0){
				for(var i=0; i<deptSelect.length; i++) {
					var node = ztree.getNodeByParam("deptid", deptSelect[i]);
					ztree.checkNode(node, true, false);
				}
				bt = 1;
			}else{
				for(var i=0; i<deptSelect.length; i++) {
					var node = ztree.getNodeByParam("deptid", deptSelect[i]);
					ztree.checkNode(node, false, false);
				}
				bt = 0;
			}

		},
		deptRelease : function() {/*部门发布*/
			var deptTreeObj = $.fn.zTree.getZTreeObj("deptTree");
            var deptNodes = deptTreeObj.getCheckedNodes(true);
			debugger
			console.log("vm.document.documentId   :"+vm.document.documentId)
			if (deptNodes.length==0) {
				alert("发布部门不能为空");
				return true;
			}
			var msg = null;
			var deptArray=[]
			if (deptNodes.length>0) {
				for(var i=0;i<deptNodes.length;i++){
					var department={}
					if(!deptNodes[i].isParent){//父节点不保存
						department.deptid=deptNodes[i].deptid
						department.deptname=deptNodes[i].name
						department.preids=deptNodes[i].preids
						deptArray.push(department)
					}
				}
				msg = "确定发布么？";
				var userdept={}
				userdept.deptArray=deptArray;
				userdept.documentId=vm.document.documentId;
				
				//
				vm.commonRelease(msg,userdept);
			}
		},
		deptTakeBack : function() {/*部门发布*/
			var deptTreeObj = $.fn.zTree.getZTreeObj("deptTree");
            var deptNodes = deptTreeObj.getCheckedNodes(true);
			debugger
			console.log("vm.document.documentId   :"+vm.document.documentId)
			if (deptNodes.length==0) {
				alert("收回部门不能为空");
				return true;
			}
			var msg = null;
			var deptArray=[]
			if (deptNodes.length>0) {
				for(var i=0;i<deptNodes.length;i++){
					var department={}
					department.deptid=deptNodes[i].deptid
					department.deptname=deptNodes[i].name
					deptArray.push(department)
				}
				msg = "确定要收回么？";
				var deptInfo={}
                deptInfo.deptArray=deptArray;
                deptInfo.documentId=vm.document.documentId;

				//收回
				vm.commonTakeBack(msg,deptInfo);
			}
		},
		commonRelease:function(msg,userdept){/*公共发布*/
			confirm(msg, function() {
				$.ajax({
					type : "POST",
					url : baseURL + "/document/documentRelease",
					dataType : "json",
					contentType : "application/json",
					data : JSON.stringify(userdept),
					success : function(result) {
						debugger
						if (result.code == 500) {
							alert(result.msg);
						} else {
							alert("发布成功!");
						}
						vm.deptSelected = null;
						vm.userSelected = null;
						vm.reload();
					}
				});
			});
		},
		commonTakeBack:function(msg,userOrDeptInfo){/*公共收回*/
            confirm(msg, function() {
                $.ajax({
                    type : "POST",
                    url : baseURL + "/document/documentTakeBack",
                    dataType : "json",
                    contentType : "application/json",
                    data : JSON.stringify(userOrDeptInfo),
                    success : function(result) {
                        debugger
                        if (result.code == 500) {
                            alert(result.msg);
                        } else {
                            alert("收回成功!");
                        }
                        vm.deptSelected = null;
                        vm.userSelected = null;
                        vm.reload();
                    }
                });
            });
        },
		getUserAndDept : function() {
			$.get(baseURL + "document/getUserAndDept", function(r) {
				vm.userList = r.userDept.userList
				vm.deptList = r.userDept.deptList
				debugger
			});
		},
		passOrFalse : function() {
			if (event) {
				var status = event.target.getAttribute("status")
				debugger
			}
			var msg = ""
			if (status == 1) {
				msg = '确定要审核通过？'
			} else {
				msg = '确定要审核不过？'
			}
			confirm(msg, function() {
				$.post(baseURL + "/document/passOrfailService", {
					"documentid" : vm.document.documentId,
					"status" : status
				}, function(result) {
					alert("操作成功");
					vm.reload();
				});
			});
		},
		getDetpMap:function(){//部门tree
			$.get(baseURL + "document/getDeptUserMap", function(r) {
				console.log(r.deptMap)
				for(var i=0;i<r.deptMap.length;i++){
					deptSelect[i] = r.deptMap[i].deptid;
				}
				var zDiv = $("#deptTree");
	             ztree = $.fn.zTree.init(zDiv, deptSetting, r.deptMap);
	             //展开所有节点
				ztree.expandAll(true);
				debugger
				if (vm.document.documentId != null) {
					vm.queryDeptIdListByDocumentId()
				}
			});
		},
		getUserMap:function(){//部门tree
			$.get(baseURL + "document/getDeptUserMap", function(r) {
				console.log(r.userMap)
				for(var i=0;i<r.userMap.length;i++){
					userSelect[i] = r.userMap[i].userid;
				}
				var zDiv = $("#userTree");
				ztree = $.fn.zTree.init(zDiv, userSetting, r.userMap);
				//展开所有节点
				ztree.expandAll(true);
				debugger
				if (vm.document.documentId != null) {
					vm.queryUserIdListByDocumentId()
				}				
			});
		},
		queryDeptIdListByDocumentId:function(){//部门id
			$.get(baseURL + "document/getDeptOrUserIdListByDocumentId", {"documentId":vm.document.documentId},function(r) {
				vm.dept.deptIdList=r.deptIdList
				
				//勾选角色所拥有的菜单
    			var depts = vm.dept.deptIdList;
    			for(var i=0; i<depts.length; i++) {
    				var node = ztree.getNodeByParam("deptid", depts[i]);
    				ztree.checkNode(node, true, false);
    			}
			});
		},
		queryUserIdListByDocumentId:function(){//用户id
			$.get(baseURL + "document/getDeptOrUserIdListByDocumentId", {"documentId":vm.document.documentId},function(r) {
				vm.user.userIdList=r.userIdList
				//勾选角色所拥有的菜单
    			var users = vm.user.userIdList;
    			for(var i=0; i<users.length; i++) {
    				var node = ztree.getNodeByParam("userid", users[i]);
    				ztree.checkNode(node, true, false);
    			}
			});
		}
	/*********** 发布  end *************/
    }
});